<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/20
 * Time: 11:46
 */

namespace app\queue\planpartimage;

use app\common\lib\Common;
use app\common\lib\MoyinTts;
use app\common\lib\RedisQueue;
use app\common\lib\TencentTts;
use app\exception\IndexException;
use app\model\image\ImageModelModel;
use app\model\novel\NovelChapterModel;
use app\model\novel\NovelChapterPartModel;
use app\model\plan\PromotionPlanModel;
use app\model\queue\AiImageRequestQueueModel;
use app\model\redis\RedisQueueModel;
use app\model\tencent\TimbreModel;
use app\model\novel\NovelPlanRoleModel;
use support\Cache;
use Webman\RedisQueue\Consumer;
use app\common\lib\TencentCos;

class AsyncPlanPartImage  implements Consumer
{
    // 要消费的队列名
    public $queue = 'asyncPlanPartImage';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    protected $resultData = [];

    // 消费
    public function consume($data)
    {
        Common::initQueueConfig();

        $queue = RedisQueueModel::getInstance()->find($data['queueid']);
        $queue->exec_time = date('Y-m-d H:i:s');
        $queue->save();

        try{
            // 无需反序列化
            //var_export($data);
            //var_export('redis_queue_asyncUploadVideo');
            $result = $this->handle($data);

            RedisQueue::getInstance()->saveQueue($this->queue,$data,$result);
        }catch (\Throwable $e){
            $cacheKey = 'async_plan_part_'.$data['requestid'];
            Cache::set($cacheKey,['progress'=>-1,'error'=>$e->getMessage()],7200);

            RedisQueue::getInstance()->saveQueue($this->queue,$data,['error'=>$e->getMessage()]);
            Common::queueExecptionReport($queue,$data,$e);
        }
    }

    protected function handle($data)
    {
        $timeLogs = [];
        $cacheKey = 'async_plan_part_'.$data['requestid'];
        Cache::set($cacheKey,['progress'=>'0'],7200);

        $first = NovelChapterPartModel::getInstance()->getWhere(['planid'=>$data['planid'],'isdel'=>0])->orderBy('batch','desc')->orderBy('number','asc')->first();
        $batch = $first['batch'];
        Cache::set($cacheKey,['progress'=>'50'],7200);

        //todo 5 生成创作内容片段-ai漫画
        $startTime = time();
        $this->generatedAIImage($data,$batch);
        Cache::set($cacheKey,['progress'=>'100'],7200);
        $timeLogs['generatedAIImage'][] = round(time()-$startTime);

        $partCount = NovelChapterPartModel::getInstance()->getWhere(['planid'=>$data['planid'],'batch'=>$batch,'isdel'=>0])->count();
        $contentText = '';
        foreach($timeLogs as $key=>$logs){
            $contentText .= $key.':'.implode(', ',$logs)."  ";
        }
        $contentLog = date('Y-m-d H:i:s') . "   ".$partCount."  ". $contentText . "\n" . "\n";
        file_put_contents(runtime_path('asyncPlanPart-time.log'), $contentLog, 8);

        return ['success'];
    }

    protected function generatedAIImage($data,$batch)
    {
        $plan = PromotionPlanModel::getInstance()->getWhere(['id'=>$data['planid']])->first();
//        $modelid = $plan['modelid']??'0';
//        $model = ImageModelModel::getInstance()->find($modelid);
//        $modelVal = $model ? $model['model'] : 'OIA Illustrator_0.10.safetensors [3328078dcc]';

        if($plan==false){
            throw new IndexException(4020,'方案不存在');
        }
        $aiImageCommands = json_decode($plan['ai_image_command'], true);
        if($aiImageCommands==false){
            throw new IndexException(4020,'生图指令JSON格式错误');
        }
        $modelVal = $aiImageCommands['override_settings']['sd_model_checkpoint']??'';
        if($modelVal==false){
            throw new IndexException(4020,'模型不能为空');
        }

        $parts = NovelChapterPartModel::getInstance()->getWhere(['planid'=>$data['planid'],'batch'=>$batch,'isdel'=>0])
            ->orderBy('number','asc')->get();

        $requestIdMap = [];
        foreach ($parts as $val){
            if(empty($val['refer_image'])){
                continue;
            }

            $prompt = $val['prompt'];
            //todo 2 根据描述词生成ai漫画图片
            if(!empty($val['roleids'])){
                $roleids = json_decode($val['roleids'],true);
                $roles = [];
                is_array($roleids) && $roles = NovelPlanRoleModel::getInstance()->getWhere([['id','in',$roleids],'isdel'=>0])->get()->toArray();
                if($roles){
                    $fixPrompt = '';
                    $endPrompt = '';
                    foreach($roles as $role){
                        $fixPrompt .=  $role['sex']==2?'1 gril,' : '1 boy,';
                        $fixPrompt .=  $role['prompt'].',';

                        $endPrompt .= ',<lora:'.$role['rola'].':1>';
                    }

                    $prompt = ($fixPrompt.$prompt.$endPrompt);
                }
            }

            $options = ['batch_size'=>'2','seed'=>($val['ai_image_command_seed']?:-1),'command_template_id'=>$plan['ai_image_command_id']??0];
            if(!empty($val['more_people_prompt'])){
                $options['more_people_prompt'] = $val['more_people_prompt'];
            }
            $aiImageCommands['init_images'] = [$val['refer_image']];
            $plan['ai_image_command'] = json_encode($aiImageCommands,256);
            $requestId = Common::generatedAIImageByTemplate($plan['ai_image_command'],$prompt,$modelVal,$options,'admin_plan_part_image_view_image_'.$val['id'],$data['requestid']??'');
            $requestIdMap[$requestId] = $val;
        }

        foreach ($requestIdMap as $requestId=>$val){
            try{
                while (true){
                    $images = Common::getAiImageResult($requestId);
                    if(!empty($images) && is_array($images)){
                        $update = [];
                        foreach($images as $k=>$image){
                            $k==0 && $update['ai_images1'] =$image;
                            $k==1 && $update['ai_images2'] =$image;
                            $k==2 && $update['ai_images3'] =$image;
                            $k==3 && $update['ai_images4'] =$image;
                        }
                        NovelChapterPartModel::getInstance()->getWhere(['id'=>$val['id']])->update($update);
                        break;
                    }
                    sleep(3);

                    $first = (new AiImageRequestQueueModel())->getWhere(['requestid'=>$requestId])->first();
                    if($first && !empty($first['start_time']) && (time()-strtotime($first['start_time']))>300){
                        break;
                    }elseif ($first==false){
                        break;
                    }
                }
            }catch (IndexException $e){
                //异常不做处理
            }
        }

        return true;
    }

    // 消费失败回调
    /*
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {
//        echo "consume failure\n";
//        echo $e->getMessage() . "\n";
//        // 无需反序列化
//        var_export($package);

        RedisQueue::getInstance()->saveQueue($this->queue,$package['data'],['error'=>$e->getMessage()]);
    }

}